package com.me.tags;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
import java.io.StringWriter;

public class FormTag extends SimpleTagSupport {
	private String controller;
	private String method;
	private String jsp_class;
	private boolean multi = false;

	@Override
	public void doTag() throws JspException, IOException {
		PageContext page = ((PageContext) this.getJspContext());
		HttpServletRequest req = (HttpServletRequest) page.getRequest();
		JspWriter out = page.getOut();
		StringWriter sw = new StringWriter();
		getJspBody().invoke(sw);
		if (controller == null || controller == "") {
			controller = req.getRequestURI().split("/")[1];
		}
		out.print(
			String.format("<form action='/%s/%s/%s' method='post' %s %s>%s</form>",
				controller.toLowerCase(),
				method,
				req.getAttribute("Model").getClass().getSimpleName(),
				multi ? "enctype=\"multipart/form-data\"" : "",
				jsp_class != "" && jsp_class != null ? String.format("class='%s'", jsp_class) : "",
				sw.toString()
			)
		);
	}

	public void setController(String controller) {
		this.controller = controller;
	}

	public void setMethod(String method) {
		this.method = method;
	}

	public void setMulti(boolean multi) {
		this.multi = multi;
	}

	public void setJsp_class(String jsp_class) {
		this.jsp_class = jsp_class;
	}
}
